package main

import (
    "fmt"
    "net"
    "strings"
)

func HandleConn(conn net.Conn)  {
    defer conn.Close()
	addr:=conn.RemoteAddr().String()
    fmt.Printf("%s connect successful.\n",addr)
	for{
        buf := make([]byte, 1024)
        n,err2:=conn.Read(buf)
        if err2!=nil{
            fmt.Println("err2",err2)
            return
        }
        fmt.Printf("Message from %s: %s\n", addr, string(buf[:n]))
        if string(buf[:n-2]) == "exit"{
            fmt.Printf("收到%s命令关闭通信",string(buf[:n-1]))
            conn.Close()
        }
        conn.Write([]byte(strings.ToUpper(string(buf[:n]))))
    }
}

func main()  {
    listener, err:=net.Listen("tcp","127.0.0.1:8000")
    if err!= nil{
        fmt.Println("err:",err)
        return
    }
    defer listener.Close()
    for{
        conn,err1:=listener.Accept()
        if err1!=nil{
            fmt.Println("err1:",err1)
            return
		}
        go HandleConn(conn)
    }
}
